<template>
  <a-row class="menu-cls">
    <a-menu
      id="DefaultSiderMenu"
      v-model:openKeys="openKeys"
      v-model:selectedKeys="selectedMenus"
      mode="inline"
      :items="menuItems"
      :style="{
        '--menu-selected-color': settingsStore.theme.colorPrimary,
        '--color-text': settingsStore.theme.colorText,
        width: '100%'
      }"
      @click="handleClickMenu"
    />
  </a-row>
</template>

<script lang="ts" setup name="DefaultSider">
import { reactive, ref, h, onMounted, watch, onUnmounted } from 'vue'
import type { MenuProps, ItemType } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { useSettingsStore } from '@/stores/settings'
import { useRouter } from 'vue-router'
import type { RoleChildrenItem } from '#/stores'
import SvgIcon from '@/components/SvgIcon/index.vue'

const router = useRouter()
const userStore = useUserStore()
const settingsStore = useSettingsStore()
const selectedMenus = ref<string[]>([userStore.currentPath])
const openKeys = ref<string[]>(userStore.getMenuOpenKeys)

let menuItems: ItemType[] = reactive([])

const handleMenus = () => {
  handleselectedMenus()
  // 处理用户权限为菜单格式
  menuItems = []
  const userRoles = userStore.getUserRoles()
  for (const roleItem of userRoles) {
    let menuItem: ItemType
    if (roleItem.hidden) return
    const showChilds = roleItem.children.filter((a) => !a.hidden)
    if (showChilds.length === 0) return
    if (!roleItem.menu) {
      menuItem = {
        key: `${roleItem.path}/${showChilds[0].path}`,
        icon: () => h(SvgIcon, { name: showChilds[0].icon }),
        label: showChilds[0].title
      }
    } else {
      menuItem = {
        key: roleItem.path,
        label: roleItem.title,
        icon: () => h(SvgIcon, { name: `${roleItem.icon}` }),
        children: showChilds.map((child: RoleChildrenItem) => {
          return {
            key: `${roleItem.path}/${child.path}`,
            icon: () => h(SvgIcon, { name: child.icon }),
            label: child.title
          }
        })
      }
    }
    menuItems.push(menuItem)
  }
}

const handleClickMenu: MenuProps['onClick'] = (e) => {
  userStore.setMenuOpenKeys(openKeys.value)
  // 点击菜单进行跳转
  router.push({
    path: `${e.key}`
  })
}

const handleselectedMenus = () => {
  // 镜像仓库列表展示镜像管理menu
  if (userStore.getCurrentPath === '/registryList/index') {
    selectedMenus.value = ['/registry/index']
  } else if (userStore.getCurrentPath === '/appDetail/index') {
    selectedMenus.value = ['/cluster/app']
  } else {
    selectedMenus.value = [userStore.currentPath]
  }
}

onMounted(() => {
  handleMenus()
})

onUnmounted(() => {})

watch(
  () => userStore.currentPath,
  () => {
    handleselectedMenus()
  }
)
watch(
  () => userStore.currentMenus,
  (val) => {
    if (val) handleMenus()
  }
)
</script>
<style lang="less" scoped>
.menu-cls {
  flex: 1 0 auto;
}
</style>
